<template>
  <a-modal
    title="成员管理"
    :width="800"
    :footer="null"
    :visible="visible"
    @cancel="onClose"
    :body-style="{ padding: '0 20px 20px 20px', height: '300px' }"
    centered
    :maskClosable="false"
  >
    <MemberMng
      :role-options="roleOptions"
      :object-id="artifactObj.uuid"
      :object-type="ResourceType.repository"
      ref="memberMngRef"
      :key="artifactObj.uuid"
    />
  </a-modal>
</template>
<script setup lang="ts">
import { artifactRolesMap } from '@/settings/commonSettings';
import { ResourceType } from '@/enums/pipelineEnum';
import { updateRoleUser } from '@/api/artifactRepository';
import { groupBy } from 'lodash';
import { ArtifactRole } from '@/enums/artifactRepositoryEnum';
import { useArtifactRepositoryStore } from '@/store/modules/artifactRepository';

const artifactRepositoryStore = useArtifactRepositoryStore();
const { artifactObj } = artifactRepositoryStore;
const roleOptions = computed(() =>
  Object.entries(artifactRolesMap).map(([key, value]) => ({ value: key, label: value })),
);
const visible = ref(false);
const memberMngRef = ref();

const getUserObjects = (arr: any = []) =>
  arr.map((item: any) => ({
    userId: item.targetUser,
    userName: item.userAttribute.userName,
  }));

const onClose = async () => {
  visible.value = false;
  const groupData = groupBy(memberMngRef.value.permissionData, 'userAttribute.role') || [];
  await updateRoleUser({
    artifactType: artifactObj.artifactType,
    artifactUuid: artifactObj.uuid,
    developerList: getUserObjects(groupData[ArtifactRole.developer]),
    managerList: getUserObjects(groupData[ArtifactRole.manager]),
    userList: getUserObjects([]),
  });
};

const onOpen = () => {
  visible.value = true;
};

defineExpose({
  onOpen,
});
</script>
